package com.redxiii.spike.pmi.command;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;

import com.redxiii.spike.api.message.ImMessage;
import com.redxiii.spike.api.pmi.entity.Issue;
import com.redxiii.spike.pmi.HandlerSession;
import com.redxiii.spike.pmi.commons.PmiSettings;
import com.redxiii.spike.pmi.commons.UserSettings;
import com.redxiii.spike.util.Formatter;
import com.redxiii.spike.util.command.InternetCommand;

/**
 * @author Daniel Filgueiras
 * 04/05/2011
 */
public abstract class GenCommitWork extends InternetCommand {
	
	protected static NumberFormat decFormat = new DecimalFormat("0.00", new DecimalFormatSymbols(Locale.US));
	
	protected UserSettings userSettings;
	protected PmiSettings pmtSettings;
	protected ImMessage message;
	
	protected String password;
	
	protected Issue issue;
	protected double	workedTime;	// in Hours
		
	public GenCommitWork() {
		pmtSettings = HandlerSession.getPmtSettings();
	}
	@Override
	public boolean proccess(ImMessage message) {
		
		this.userSettings = HandlerSession.getUserSettings(remoteId);
		this.message = message;
		
		if (!hasAccess(message) || !isWorking(message))
			return false;
		
		if (commit()) {
			Formatter formatter = new Formatter();
			
			StringBuilder buffer = new StringBuilder()
				.append("Issue #").append(issue.getId()).append(" updated: *\"")
				.append(issue.getSummary()).append("\"* \r\n")
				.append("Worked ")
				.append(formatter.formatTimeInSecondsToHour((long)(workedTime * 60L * 60L)));
			
			service.reply(message, buffer);
			userSettings.resetWork();
			return true;
		}
		
		return false;
	}
	
	protected abstract boolean commit();
	
	
	protected boolean hasAccess(ImMessage message) {
		boolean canCommitWork = true; 

		return canCommitWork;
	}
	
	protected boolean isWorking(ImMessage message) {
		
		long issueNumber = userSettings.getWorkingIssue();
		workedTime = (userSettings.getWorkedTime() / 1000f / 60f / 60f);
		
		if (issueNumber == 0 || workedTime == 0) {
			service.reply(message, "You are not working on any issue OR worked less then a minute");
			return false;
		}

		issue = HandlerSession.getDatabase().getIssue(issueNumber);
		if (issue == null) {
			service.reply(message, "Unknown issue");
			return false;
		}
		
		return true;
	}
}
